package com.yfbao.horizon.inspection.engine.impl;

import com.yfbao.horizon.inspection.config.InspectConfig;
import com.yfbao.horizon.inspection.config.ReportTaskConfig;
import com.yfbao.horizon.inspection.dto.ReportDto;
import com.yfbao.horizon.inspection.dto.ReportInfoResult;
import com.yfbao.horizon.inspection.dto.ReportResult;
import com.yfbao.horizon.inspection.entity.SystemInspectRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 生命周期引擎实现类
 * 负责按照生命周期存储配置，定期删除过期数据
 */
@Component
public class LifeCycleEngine extends AbstractInspectEngine<ReportInfoResult> {

    private static final Logger logger = LoggerFactory.getLogger(LifeCycleEngine.class);

    /**
     * 引擎编码
     */
    private static final String ENGINE_CODE = "lifecycle_engine";

    /**
     * 模拟存储的检测记录
     * 实际应用中，这里应该通过数据库访问层操作
     */
    private final Map<String, List<SystemInspectRecord>> recordStore = new ConcurrentHashMap<>();

    /**
     * 模拟存储的任务配置
     * 实际应用中，这里应该通过数据库访问层操作
     */
    private final Map<String, ReportTaskConfig> taskConfigStore = new ConcurrentHashMap<>();

    @Override
    public String getCode() {
        return ENGINE_CODE;
    }

    @Override
    public List<ReportInfoResult> getReportInfo(String taskNo) {
        logger.info("获取生命周期任务 {} 的报告详情", taskNo);
        List<ReportInfoResult> infoList = new ArrayList<>();
        
        // 查询与该任务相关的所有记录
        for (Map.Entry<String, List<SystemInspectRecord>> entry : recordStore.entrySet()) {
            for (SystemInspectRecord record : entry.getValue()) {
                ReportTaskConfig config = taskConfigStore.get(record.getInspectCategory());
                if (config != null && config.getTaskCode().equals(taskNo)) {
                    ReportInfoResult info = new ReportInfoResult();
                    info.setTaskNo(taskNo);
                    info.setEnv(record.getInspectEnv());
                    info.setInspectCategory(record.getInspectCategory());
                    info.setInspectItem(record.getInspectItem());
                    info.setCaption("生命周期管理");
                    info.setLabel(record.getInspectItemDesc());
                    info.setLevel(convertLevel(record.getInspectItemResult()));
                    info.setMessage(record.getInspectItemResult());
                    info.setSort(1);
                    info.setCollectTime(record.getCollectTime().toString());
                    infoList.add(info);
                }
            }
        }
        
        return infoList;
    }

    @Override
    public ReportDto inspectCustomerReportResult(InspectConfig config, ReportTaskConfig reportConfig) {
        logger.info("执行自定义生命周期报告生成，任务编号: {}, 环境: {}", config.getTaskNo(), config.getInspectEnv());
        
        // 生成生命周期管理报告
        List<ReportInfoResult> infoList = new ArrayList<>();
        ReportInfoResult info = new ReportInfoResult();
        info.setTaskNo(config.getTaskNo());
        info.setEnv(config.getInspectEnv());
        info.setInspectCategory("lifecycle");
        info.setInspectItem("data_cleanup");
        info.setCaption("数据清理");
        info.setLabel("自定义生命周期数据清理");
        info.setLevel("none");
        info.setMessage("normal");
        info.setSort(1);
        info.setCollectTime(LocalDateTime.now().toString());
        infoList.add(info);
        
        ReportResult reportResult = createReportResult(config, reportConfig, "normal");
        reportResult.setInspectDesc("自定义生命周期管理报告");
        
        return createReportDto(reportResult, infoList);
    }

    @Override
    public ReportDto inspectReportResult(InspectConfig config, ReportTaskConfig reportConfig) {
        logger.info("执行规则生命周期报告生成，任务编号: {}, 环境: {}", config.getTaskNo(), config.getInspectEnv());
        
        // 生成生命周期管理报告
        List<ReportInfoResult> infoList = new ArrayList<>();
        ReportInfoResult info = new ReportInfoResult();
        info.setTaskNo(config.getTaskNo());
        info.setEnv(config.getInspectEnv());
        info.setInspectCategory("lifecycle");
        info.setInspectItem("data_cleanup");
        info.setCaption("数据清理");
        info.setLabel("规则生命周期数据清理");
        info.setLevel("none");
        info.setMessage("normal");
        info.setSort(1);
        info.setCollectTime(LocalDateTime.now().toString());
        infoList.add(info);
        
        ReportResult reportResult = createReportResult(config, reportConfig, "normal");
        reportResult.setInspectDesc("规则生命周期管理报告");
        
        return createReportDto(reportResult, infoList);
    }

    @Override
    public SystemInspectRecord inspectCustomerCollect(InspectConfig config) {
        logger.info("执行自定义生命周期数据收集，配置: {}, 环境: {}", config.getInspectItem(), config.getInspectEnv());
        return doInspect(config);
    }

    @Override
    public SystemInspectRecord inspectCollect(InspectConfig config) {
        logger.info("执行规则生命周期数据收集，配置: {}, 环境: {}", config.getInspectItem(), config.getInspectEnv());
        return doInspect(config);
    }

    @Override
    public void inspectPeriodScan(InspectConfig config) {
        logger.info("执行生命周期周期扫描，配置: {}, 环境: {}", config.getInspectItem(), config.getInspectEnv());
        
        // 执行数据清理
        cleanupExpiredData();
        
        logger.info("生命周期周期扫描完成");
    }

    @Override
    protected SystemInspectRecord doInspect(InspectConfig config) {
        SystemInspectRecord record = new SystemInspectRecord();
        record.setInspectEnv(config.getInspectEnv());
        record.setInspectCategory("lifecycle");
        record.setInspectItem("data_cleanup");
        record.setInspectItemResult("normal");
        record.setInspectItemValue("0");
        record.setInspectItemDesc("生命周期管理数据收集");
        record.setCollectTime(LocalDateTime.now());
        
        // 保存到模拟存储中
        String key = config.getInspectEnv() + ":" + config.getInspectCategory();
        recordStore.computeIfAbsent(key, k -> new ArrayList<>()).add(record);
        
        return record;
    }

    /**
     * 清理过期数据
     */
    public void cleanupExpiredData() {
        logger.info("开始清理过期数据");
        int totalDeleted = 0;
        
        // 遍历所有存储的记录
        for (Map.Entry<String, List<SystemInspectRecord>> entry : recordStore.entrySet()) {
            String key = entry.getKey();
            List<SystemInspectRecord> records = entry.getValue();
            
            // 获取对应的任务配置
            String category = key.split(":")[1];
            ReportTaskConfig config = taskConfigStore.get(category);
            
            if (config != null && config.getStorageCycle() > 0) {
                // 计算过期时间
                LocalDateTime expireTime = LocalDateTime.now().minus(config.getStorageCycle(), ChronoUnit.DAYS);
                
                // 删除过期记录
                List<SystemInspectRecord> expiredRecords = records.stream()
                        .filter(record -> record.getCollectTime().isBefore(expireTime))
                        .collect(Collectors.toList());
                
                records.removeAll(expiredRecords);
                totalDeleted += expiredRecords.size();
                
                logger.info("已删除类别 {} 的过期记录 {} 条，存储周期: {} 天", 
                        category, expiredRecords.size(), config.getStorageCycle());
            }
        }
        
        logger.info("过期数据清理完成，共删除 {} 条记录", totalDeleted);
    }

    /**
     * 注册任务配置
     * @param taskConfig 任务配置
     */
    public void registerTaskConfig(ReportTaskConfig taskConfig) {
        taskConfigStore.put(taskConfig.getTaskCode(), taskConfig);
        logger.info("注册任务配置，任务编号: {}, 存储周期: {} 天", 
                taskConfig.getTaskCode(), taskConfig.getStorageCycle());
    }

    /**
     * 获取当前存储的记录数量
     * @return 记录数量
     */
    public int getRecordCount() {
        return recordStore.values().stream().mapToInt(List::size).sum();
    }
}